package myschool.test3;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;
import java.io.*;
/**
 * @author oldliu
 * @since 1.0
 */
public class WavHeader {
    /**
     * RIFF数据块
     */
    final String riffChunkId = "RIFF";
    int riffChunkSize;
    final String riffType = "WAVE";

    /**
     * FORMAT 数据块
     */
    final String formatChunkId = "fmt ";
    final int formatChunkSize = 16;
    final short audioFormat = 1;
    short mChannels;
    int mSampleRate;
    int mByteRate;
    short mBlockAlign;
    short mSampleBits;

    /**
     * FORMAT 数据块
     */
    final String mDataChunkId = "data";
    int dataChunkSize;

    WavHeader(int totalAudioLen, int sampleRate, short channels, short sampleBits) {
        this.riffChunkSize = totalAudioLen + 44 - 8;
        this.mChannels = channels;
        this.mSampleRate = sampleRate;
        this.mByteRate = sampleRate * sampleBits * channels / 8;
        this.mBlockAlign = (short) (channels * sampleBits / 8);
        this.mSampleBits = sampleBits;
        this.dataChunkSize = totalAudioLen;
    }

    public byte[] getHeader() {
        ByteBuffer buffer = ByteBuffer.allocate(44);
        buffer = buffer.order(ByteOrder.LITTLE_ENDIAN);
        buffer.put(riffChunkId.getBytes(StandardCharsets.UTF_8)); // The "RIFF" chunk descriptor
        buffer.putInt(riffChunkSize);  // ChunkSize 下个地址开始到文件尾的总字节数(此Chunk的数据大小)
        buffer.put(riffType.getBytes(StandardCharsets.UTF_8)); // "WAVE"
        buffer.put(formatChunkId.getBytes(StandardCharsets.UTF_8)); // "fmt + 空格"
        buffer.putInt(formatChunkSize); // SubChunkSize1 一般为16
        buffer.putShort(audioFormat); // 1：表示是PCM 编码
        buffer.putShort(mChannels); // 通道
        buffer.putInt(mSampleRate); // 采样率
        buffer.putInt(mByteRate); // 码率：采样率 * 采样位数 * 声道个数，bytePerSecond = sampleRate * (bitsPerSample / 8) * channels
        buffer.putShort(mBlockAlign); // 每次采样的大小：采样位数*声道数/8
        buffer.putShort(mSampleBits); // 采样位数
        buffer.put(mDataChunkId.getBytes(StandardCharsets.UTF_8)); // "data"
        buffer.putInt(dataChunkSize); // 音频数据长度
        buffer.flip();
        return buffer.array();
    }


/*
@param sampleRate 采样率
@param channels 通道个数，1 单通道 2 双通道...
@param sampleBits 每次采样的数据位数 一般为16位
@param pcmPath  pcm 文件路径
@param  destinationPath 输出的wav文件路径
 */

    public static void convertPCMFileToWAVFile(int sampleRate, short channels, short sampleBits, String pcmPath, String destinationPath) throws IOException {
        File pcmFile = new File(pcmPath);
        if (!pcmFile.exists()) {
            throw new FileNotFoundException();
        }
        // 先删除目标文件
        File wavFile = new File(destinationPath);
        if (wavFile.exists()) {
            wavFile.delete();
        }
        int nTotalAudioSize = (int) pcmFile.length();
        WavHeader header = new WavHeader(nTotalAudioSize, sampleRate, channels, sampleBits);
        byte[] buffer = new byte[1024 * 4]; // Length of All Files, Total Size

        InputStream inStream = new BufferedInputStream(new FileInputStream(pcmFile));
        OutputStream outStream = new BufferedOutputStream(new FileOutputStream(wavFile));

        // 写入WAVFile 头部
        try {
            outStream.write(header.getHeader());
            // 循环读入数据
            do {
                int size = inStream.read(buffer);
                if (size != -1) {
                    outStream.write(buffer, 0, size);
                } else {
                    break;
                }
            } while (true);
        } catch (IOException e) { // 写入头部失败
            throw e;
        } finally {
            try {
                inStream.close();
                outStream.close();
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
        System.out.println("PcmToWav"+ "makePCMFileToWAVFile  success!" + new SimpleDateFormat("yyyy-MM-dd hh:mm").format(new Date()));
    }

    public static void main(String[] args) {
        try {
            convertPCMFileToWAVFile( 16000,(short)1,(short)16,"D:\\Documents\\桌面\\tts_ws_java_demo\\src\\main" +
                    "\\resources\\tts\\1686214886044.pcm","D:\\Documents\\桌面\\tts_ws_java_demo\\src\\main\\resources" +
                    "\\tts\\1.wav");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}